package com.shiro.demo0929.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.sun.org.apache.bcel.internal.generic.RET;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @date 2020/9/29 19:41
 */
@Configuration
public class ShiroConfig {

    /**
     * 设置安全管理器，一般用来过滤请求
     * @param defaultWebSecurityManager
     * @return
     */
    @Bean(name = "shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();

//        关联 shiroFilterFactoryBean
        bean.setSecurityManager(defaultWebSecurityManager);

//        添加内置过滤器
        /*
         * anon 无需认证就访问
         * authc 认证之后才能访问
         * user 必须拥有记住我功能才能用
         * perms 拥有对某个资源的权限才能访问
         * role 拥有某个角色权限才能访问
         */
        Map<String ,String > filterMap = new LinkedHashMap<>();
        filterMap.put("/toLogin","anon");
        filterMap.put("/","anon");
        filterMap.put("/hello","authc");
//        有什么权限可以访问什么
        filterMap.put("/user","perms[ROLE_USER]");
        filterMap.put("/admin","perms[ROLE_ADMIN]");
//       设置需要拦截的url
        bean.setFilterChainDefinitionMap(filterMap);

//        设置登录请求
        bean.setLoginUrl("/toLogin");

//        设置未授权执行的请求
        bean.setUnauthorizedUrl("/unauthorized");

        return bean;
    }


    /**
     * 获取 DefaultWebSecurityManager
     * @return
     */
    @Bean(name = "defaultWebSecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        // 关联realm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    /**
     * 将自定义的realm交给spring托管，认证
     * @return
     */
    @Bean(name = "userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }


    /**
     * shiro整合thymeleaf
     * @return
     */
    @Bean(name = "shiroDialect")
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }

}
